<template>
  <view class="comBox">
    <sickTitleCom></sickTitleCom>
    <view class="body">
      <view class="name titleBold">1.您是否患有以下疾病（可多选，必填）</view>
      <view class="sickList">
        <view
          v-for="item in ownSickList"
          :key="item.id"
          :class="[item.active ? 'sickSpan cur' : 'sickSpan']"
          @click="choseList(item)"
        >
          {{ item.name }}
          <span v-if="item.active" class="curImg"><img :src="curIcon" /></span>
        </view>
        <view :class="[checkHealthBtn ? 'sickSpan cur' : 'sickSpan', 'rowBlock']" @click="clearChose">
          健康
          <span v-if="checkHealthBtn" class="curImg"><img :src="curIcon" /></span>
        </view>
      </view>
    </view>

    <view v-if="checkDisease" class="body checkDisease">
      <view class="name titleBold">目前是否在服药物？</view>
      <view class="sickList">
        <view :class="[takeMedicine === true ? 'cur' : '', 'sickSpan mRadioItem']" @click="choseTakeMedicine(true)">
          是
          <span v-if="takeMedicine === true" class="curImg"><img :src="curIcon" /></span>
        </view>
        <view :class="[takeMedicine === false ? 'cur' : '', 'sickSpan mRadioItem']" @click="choseTakeMedicine(false)">
          否
          <span v-if="takeMedicine === false" class="curImg"><img :src="curIcon" /></span>
        </view>
      </view>
    </view>

    <view v-if="takeMedicine" class="body">
      <view class="name titleBold">请输入在服药物清单</view>
      <view class="r-addm" @click="chooseMedicine">添加药品</view>
      <div class="drugs-list">
        <div v-for="(item, index) in assessMedicine" :key="item.baseDrugId" class="drug-box">
          <image class="icon" :src="icon" @click="delDrug(index)"></image>
          <!-- <icon class="icon" type="close" size="26" @click="delDrug(key)"></icon> -->
          <image v-if="item.outerPackagePicUrl" class="drug-img" :src="item.outerPackagePicUrl"></image>
          <image v-else class="drug-img" :src="zwtp"></image>
          <div class="drug-info">
            <div class="title">{{ item.commonName }}</div>

            <div class="spe">
              {{ item.preparationUnit }}*{{ item.packageSize }}{{ item.minimumUnit }}/{{ item.packageUnit }}
            </div>

            <view class="usage">
              <text>每天吃几次</text>
              <view class="sele">
                <picker
                  class="select-view"
                  mode="selector"
                  :value="dayFrequencySelectObj[index] || 0"
                  :range="dayFrequencyArray"
                  @change="bindMultiPickerChange(index, $event)"
                >
                  <view :class="[dayFrequencySelectObj[index] !== Number(0) ? 'select-con' : '']">
                    {{ dayFrequencyArray[dayFrequencySelectObj[index] || 0] }}
                    <image class="position-icon" :src="down"></image>
                  </view>
                </picker>
              </view>
            </view>
            <view class="every">
              <text>每次吃几粒</text>
              <view class="every-view">
                <div class="add" @click="min(index)">-</div>
                <div class="num">{{ everyTimeObj[index] || 1 }}</div>
                <div class="add" @click="add(index)">+</div>
              </view>
            </view>
            <view v-for="sIndex of timeFrequencyArray[dayFrequencySelectObj[index]]" :key="sIndex" class="usage">
              <text>用药时间</text>
              <view class="sele">
                <picker
                  class="select-view"
                  mode="selector"
                  :value="(timeSelectObj[index] && timeSelectObj[index][sIndex]) || 13"
                  :range="timeArray"
                  @change="timePickerChange(index, sIndex, $event)"
                >
                  <view
                    :class="[timeSelectObj[index] && timeSelectObj[index][sIndex] !== Number(0) ? 'select-con' : '']"
                  >
                    {{ timeArray[(timeSelectObj[index] && timeSelectObj[index][sIndex]) || 13] }}
                    <image class="position-icon" :src="down"></image>
                  </view>
                </picker>
              </view>
            </view>
          </div>
        </div>
      </div>
    </view>

    <view class="body secondBody">
      <!-- 原来第5题 -->
      <view class="titleBold">2.您的父母、子女、兄弟姐妹是否患过以下疾病（可多选）:</view>
      <view class="sickList">
        <view
          v-for="item in familySickList"
          :key="item.id"
          :class="[item.active ? 'sickSpan cur' : 'sickSpan']"
          @click="choseFamilyList(item)"
        >
          {{ item.name }}
          <span v-if="item.active" class="curImg"><img :src="curIcon" /></span>
        </view>
        <view :class="[familyNoChose ? 'sickSpan cur' : 'sickSpan', 'rowBlock']" @click="clearFamilyChose">
          均未患上述疾病
          <span v-if="familyNoChose" class="curImg"><img :src="curIcon" /></span>
        </view>
      </view>
      <!-- 下一题上一题按钮 -->
      <nextProBtnCom @nextBtn="nextBtn" @proBtn="proBtn"></nextProBtnCom>
    </view>
  </view>
</template>

<script>
import { getAssessDiseases, sendPrescription } from '@/api/assessQuestion';
import nextProBtnCom from '@/components/nextProButton';
import sickTitleCom from './sickTitleCom';
import curIcon from '@/static/icon/cur.png';
import { ajaxSend } from './ajaxHealth.js';
import { mapGetters } from 'vuex';
import down from '@/static/icon/a-down.png';
import icon from '@/static/icon/close2.png';
export default {
  components: {
    // 上一题下一题组件
    nextProBtnCom,
    sickTitleCom
  },
  props: {
    // uSex: {
    //   type: String,
    //   default: ''
    // }
  },
  data() {
    return {
      zwtp: 'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-community/zwtp.png',
      down,
      icon,
      mainData: {},
      ownSickList: [],
      familySickList: [],
      curIcon: curIcon,
      checkHealthBtn: false,
      checkDisease: false,
      familyNoChose: false,
      takeMedicine: undefined,
      dayFrequency: '',
      dayFrequencyArray: ['请选择', '每日一次', '每日两次', '每日三次', '每日四次', '每夜一次', '每周一次'],
      timeFrequencyArray: [1, 1, 2, 3, 4, 1, 1],
      timeArray: [
        '请选择',
        '0:00',
        '1:00',
        '2:00',
        '3:00',
        '4:00',
        '5:00',
        '6:00',
        '7:00',
        '8:00',
        '9:00',
        '10:00',
        '11:00',
        '12:00',
        '13:00',
        '14:00',
        '15:00',
        '16:00',
        '17:00',
        '18:00',
        '19:00',
        '20:00',
        '21:00',
        '22:00',
        '23:00'
      ],
      dayFrequencySelectObj: {},
      timeSelectObj: {},
      everyTimeObj: {} // 每次吃几粒
    };
  },
  computed: {
    ...mapGetters(['active', 'assessForm', 'userSex', 'assessMedicine']),
    assessPatientId() {
      return this.$store.getters.assessPatientId || wx.getStorageSync('assessPatientId');
    }
  },
  mounted() {
    this.getDiseases();
    console.log('assessMedicine:', this.assessMedicine);
  },
  methods: {
    chooseMedicine() {
      this.$wxPromise.navigateTo({
        url: '/pages/searchDrug/index'
      });
    },
    min(index) {
      let everyTime = this.everyTimeObj[index] || 1;
      if (everyTime <= 0.5) return;
      everyTime -= 0.5;
      this.$set(this.everyTimeObj, index, everyTime);
    },

    add(index) {
      // console.log('add item:', index);
      let everyTime = this.everyTimeObj[index] || 1;
      everyTime += 0.5;
      this.$set(this.everyTimeObj, index, everyTime);
    },
    // 每天吃几次选择弹窗
    bindMultiPickerChange(index, e) {
      console.log('e:', e);
      // console.log('dayFrequencyIndex:', item.dayFrequencyIndex);
      // this.dayFrequencySelectObj[index] = e.detail.value;
      this.$set(this.dayFrequencySelectObj, index, e.detail.value);
      // 初始化用药时间 获取每天几次
      let frequence = this.timeFrequencyArray[e.detail.value];
      let sAnswer = {};
      for (let i = 0; i < frequence; i++) {
        sAnswer[i] = 13;
      }
      this.$set(this.timeSelectObj, index, sAnswer);
      // 初始化用量
      this.$set(this.everyTimeObj, index, 1);
      // console.log('this.dayFrequencySelectObj:', this.dayFrequencySelectObj);
      // console.log('this.timeSelectObj:', this.timeSelectObj);
      // item.dayFrequencyIndex = e.detail.value;
      // item.dayFrequencyIndex = e.detail.value;
    },
    timePickerChange(index, sIndex, e) {
      // item.medicineTimeIndex = e.detail.value;
      let sAnswer = this.timeSelectObj[index] || {};
      sAnswer[sIndex] = e.detail.value;
      this.$set(this.timeSelectObj, index, sAnswer);
      // console.log('item.timeSelectObj:', this.timeSelectObj);
    },
    choseTakeMedicine(value) {
      this.takeMedicine = value;
    },
    async nextBtn() {
      // 疾病直接提交接口
      let ownData = [];
      let isHaveDiabetes = false;
      let icd10Item = [];
      let selectOwnDiseasesId = [];
      this.ownSickList.forEach((item) => {
        if (item.active) {
          let obj = {
            diseaseId: item.icd10
          };
          icd10Item.push(item.icd10);
          ownData.push(obj);
          selectOwnDiseasesId.push({
            diseaseId: item.id
          });
          if (item.name.indexOf('糖尿病') > 0) {
            isHaveDiabetes = true;
          }
        }
      });
      if (ownData.length < 1 && !this.checkHealthBtn) {
        uni.showToast({ title: `请选择您是否患病`, icon: 'none' });
        return false;
      }

      // 用药信息校验
      // 选择了有病
      if (icd10Item.length > 0) {
        if (this.takeMedicine === undefined) {
          uni.showToast({ title: `是否在服药不能为空`, icon: 'none' });
          return;
        } else if (this.takeMedicine === true) {
          // 选择药品
          if (this.assessMedicine.length === 0) {
            uni.showToast({ title: `药品信息不能为空`, icon: 'none' });
            return;
          }
          // 选择了疾病
          if (Object.keys(this.dayFrequencySelectObj).length === 0) {
            uni.showToast({ title: `每天吃几次不能为空`, icon: 'none' });
            return;
          } else {
            let frequencyUndefinedIndex = this.assessMedicine.findIndex((item, index) => {
              return !this.dayFrequencySelectObj[index] || this.dayFrequencySelectObj[index] === '0';
            });
            if (frequencyUndefinedIndex !== -1) {
              uni.showToast({ title: `第${frequencyUndefinedIndex + 1}个药品每日吃几次不能为空`, icon: 'none' });
              return;
            }
          }

          // 提交用药需求
          let prescriptionData = {
            patientId: this.assessPatientId, // 会员id
            diseases: selectOwnDiseasesId, // 诊断
            drugs: this.assessMedicine.map((item, index) => {
              // console.log('index:', index);
              // console.log('this.timeSelectObj:', this.timeSelectObj);
              return {
                baseDrugId: item.baseDrugId,
                price: item.priceCent,
                usage: this.dayFrequencySelectObj[index],
                dosage: this.everyTimeObj[index],
                number: 1,
                medicationTimeList: Object.values(this.timeSelectObj[index]).map((item) => {
                  return item - 1 + ':00';
                })
              };
            }), // 药品

            channel: '7' // 来源
          };
          // console.log('prescriptionData:', prescriptionData);
          await sendPrescription(prescriptionData);
        }
      }

      // 家人患病校验

      let familyOwnData = [];
      let familyIcd10Item = [];
      this.familySickList.forEach((item) => {
        if (item.active) {
          let obj = {
            diseaseId: item.icd10,
            relation: 17
          };
          familyIcd10Item.push(item.icd10);
          familyOwnData.push(obj);
        }
      });
      if (familyOwnData.length < 1 && !this.familyNoChose) {
        uni.showToast({ title: `请选择家人是否患病`, icon: 'none' });
        return false;
      }
      // console.log('selectOwnDiseasesId:', selectOwnDiseasesId);

      // 获取健康指标指导意见 判断是出健康提示还是直接下一步 start
      const healthData = await ajaxSend({ chronicDiseases: icd10Item, homeMedicalHistories: familyIcd10Item });
      if (healthData && healthData.length > 0) {
        // 如果有异常，则提示
        this.$store.commit('assessQuestion/SET_AJAXRESMESSAGE', healthData); // 存提示信息到vux，数组格式
        this.$store.commit('assessQuestion/SET_AJAXRES', true); // 开启提示
      } else {
        this.$store.commit('assessQuestion/SET_ISHAVEDISABETES', isHaveDiabetes);
        // let curActive = this.active + 1;
        this.$store.commit('assessQuestion/SET_ACTIVE', 2);
      }
      // console.log('ownData:', ownData);
      // console.log('familyOwnData:', familyOwnData);
      this.$store.commit('assessQuestion/SET_OWNSICKLIST', ownData);
      this.$store.commit('assessQuestion/SET_FAMILYSICKLIST', familyOwnData);
      // 获取健康指标指导意见 判断是出健康提示还是直接下一步 end
      wx.pageScrollTo({
        scrollTop: 0
      });
    },
    proBtn() {
      // let curActive = this.active - 1;
      this.$store.commit('assessQuestion/SET_ACTIVE', 0);
    },
    getDiseases() {
      getAssessDiseases().then((res) => {
        if (res.code === 0) {
          let main = res.data.own;
          main.forEach((item, index) => {
            main[index].active = false;
          });
          // 只显示以下疾病,其他疾病不显示
          // let beDiseases = [
          //   '高血压',
          //   '2型糖尿病',
          //   '1型糖尿病',
          //   '高血脂',
          //   '冠心病',
          //   '脑梗死',
          //   '脑出血',
          //   '痛风',
          //   '心肌梗死',
          //   '心衰'
          // ];
          main = main.filter((item) => {
            return item.icd10[0] !== 'C' && item.icd10 !== 'B24' && item.icd10 !== 'F20';
          });
          if (this.userSex === '男') {
            main = main.filter(
              (item) =>
                item.name !== '乳腺癌' &&
                item.name !== '宫颈癌' &&
                item.name !== '卵巢癌' &&
                item.name !== '子宫癌' &&
                item.name !== '宫颈2、3级上皮内瘤变' &&
                item.name !== '乳腺重度非典型增生' &&
                item.name !== '乳管内乳头瘤变'
            );
          }
          if (this.userSex === '女') {
            main = main.filter((item) => item.name.indexOf('前列腺癌') === -1);
          }
          this.ownSickList = main;
          // const otherSickData = {
          //   active: false,
          //   chronicDiseases: [],
          //   diseaseId: '',
          //   icd10: 'otherSickOwn',
          //   id: 'otherSickOwn',
          //   key: 'otherSickOwn',
          //   name: '其他疾病'
          // };
          // // console.log('疾病列表', this.ownSickList);
          // this.ownSickList.push(otherSickData);

          let familyMain = res.data.family;
          familyMain.forEach((item, index) => {
            familyMain[index].active = false;
          });
          this.familySickList = familyMain;
        }
      });
    },
    choseList(val) {
      this.checkHealthBtn = false;
      this.checkDisease = true;
      if (val.id === 'otherSickOwn') {
        this.ownSickList.forEach((item, index) => {
          this.ownSickList[index].active = false;
        });
      } else {
        const indexs = this.ownSickList.findIndex((item) => item.id === 'otherSickOwn');
        if (indexs > -1) {
          this.ownSickList[indexs].active = false;
        }
      }
      const indexs = this.ownSickList.findIndex((item) => item.id === val.id);
      this.ownSickList[indexs].active = !this.ownSickList[indexs].active;
    },
    choseFamilyList(val) {
      this.familyNoChose = false;
      const indexs = this.familySickList.findIndex((item) => item.id === val.id);
      this.familySickList[indexs].active = !this.familySickList[indexs].active;
    },
    clearChose() {
      this.checkDisease = false;
      this.takeMedicine = false;
      if (this.checkHealthBtn) {
        this.checkHealthBtn = false;
        return;
      }
      this.ownSickList.forEach((item, index) => {
        this.ownSickList[index].active = false;
      });
      this.checkHealthBtn = true;
    },
    clearFamilyChose() {
      if (this.familyNoChose) {
        this.familyNoChose = false;
        return;
      }
      this.familySickList.forEach((item, index) => {
        this.familySickList[index].active = false;
      });
      this.familyNoChose = true;
    },
    // 删除药品
    delDrug(index) {
      this.assessMedicine.splice(index, 1);
      this.$store.commit('assessQuestion/SET_ASSESSMEDICINE', this.assessMedicine);
    }
  }
};
</script>
<style lang="scss">
@import './../style/sickOwnFam.scss';
.drugs-list {
  margin-top: 12rpx;
  .drug-box {
    // background: #ffffff;
    padding: 30rpx 0rpx;
    box-sizing: border-box;
    position: relative;
    display: flex;
    margin: 24rpx 0rpx;
    // box-shadow: rgba(0, 0, 0, 0.05) 0px 4rpx 8rpx 0px;
    border-bottom: 2rpx solid #b2b2b2;
    .icon {
      width: 40rpx;
      height: 40rpx;
      position: absolute;
      top: 47rpx;
      right: 0rpx;
    }
  }
  .drug-img {
    width: 120rpx;
    height: 120rpx;
    border-radius: 8rpx;
    margin-right: 28rpx;
    flex-shrink: 0;
  }
  .drug-info {
    flex: 1;
    .title {
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      font-size: 32rpx;
      color: #222222;
      line-height: 1.3em;
      margin-bottom: 8rpx;
      font-weight: bolder;
    }
    .spe {
      font-size: 28rpx;
      color: #b2b2b2;
      margin-bottom: 28rpx;
    }
    .fre {
      font-size: 28rpx;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.6);
    }
    .usage {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 28rpx;
      color: rgba(0, 0, 0, 0.6);
      margin-bottom: 32rpx;
    }
    .sele {
    }
    .step {
      width: 320rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-left: 40rpx;
      .btn {
        width: 88rpx;
        height: 56rpx;
        background: #f3f3f3;
        border-radius: 8rpx;
        text-align: center;
        line-height: 46rpx;
        font-size: 40rpx;
      }
    }
    .select-view {
      width: 320rpx;
      height: 56rpx;
      background: #f4f4f4;
      border-radius: 8rpx;
      line-height: 56rpx;
      text-align: center;
      position: relative;
      padding-right: 40rpx;
      box-sizing: border-box;
    }
    .select-con {
      color: rgba(0, 0, 0, 0.9);
    }
    .position-icon {
      width: 32rpx;
      height: 32rpx;
      position: absolute;
      top: 50%;
      margin: -19rpx 0 0;
      right: 2px;
    }
    .every {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 28rpx;
      color: rgba(0, 0, 0, 0.6);
      margin-bottom: 32rpx;
    }
    .every-view {
      width: 320rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .add {
      width: 88rpx;
      height: 56rpx;
      background: #f4f4f4;
      border-radius: 8px;
      font-size: 36rpx;
      text-align: center;
      color: rgba(0, 0, 0, 0.9);
    }
    .num {
      color: rgba(0, 0, 0, 0.9);
    }
  }
}
.body {
  .titleBold {
  }
  .sickList {
    .mRadioItem {
      width: 30%;
      text-align: center;
    }
  }
  .r-addm {
    width: 100%;
    text-align: center;
    border: 2rpx solid #f25559;
    color: #f25559;
    padding: 10rpx 18rpx;
    /* margin: 12rpx 16rpx; */
    border-radius: 16rpx;
    font-size: 28rpx;
    position: relative;
    box-sizing: border-box;
  }
}
</style>
